from django.template import Context, loader
from django.http import HttpResponse
from grocery.models import Item, Store

def mklnk (item, s):
    return '<a href="/grocery/%s/%s/">%s</a>' % (item.id, s, item.name)

def index (req):
    il = Item.objects.filter (quantity__gte=1)
    t = loader.get_template ('grocery/start.html')
    c = Context({
        'grocery_list': il,
        'link': '/grocery/add/',
    })
    return HttpResponse(t.render(c))

def add (req):
    il = Item.objects.filter (quantity=0)
    t = loader.get_template ('grocery/start.html')
    c = Context({
        'grocery_list': il,
        'link': '/grocery/new_add/',
    })
    return HttpResponse(t.render(c))

def inadd (req):
    il = Item.objects.filter (quantity=0)
    t = loader.get_template ('grocery/start.html')
    c = Context({
        'grocery_list': il,
        'link': '/grocery/add/',
    })
    return HttpResponse(t.render(c))

def detail (req, item):
    i = Item.objects.get (id=item)
    #s = str (dir (i.store)) + str (i.store.values ())
    s = ', '.join ([mklnk (p, 'bystore') for p in i.store.iterator ()])
    return HttpResponse('So curious..bout "%s" in stores %s huh?' % (i.name, s))

def bystore (req, store):
    s = Store.objects.get (id=store)
    il = Item.objects.filter (store__in=[s])
    o = '<p/>'.join ([mklnk (p, 'detail') for p in il])
    return HttpResponse('So curious..store-> "%s" hmm..<br/>%s?' % (store, o))

